from collections import OrderedDict
from datetime import datetime
from time import time
import json

from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from apps.publish.models import *
from .serializer import *
from util.auth import OWNTokenAuthentication
from util.page import MyPageNumberPagination
from util.exception import ValidationError
from util.svn_tool import SvnExport
from .models import *


class DevicesView(GenericViewSet):
    authentication_classes = [OWNTokenAuthentication]

    @action(detail=False, methods=["GET", ], url_path="device_list")
    def device_list(self, requests, *args, **kwargs):
        product_name = requests.GET.get("product_name")
        product_number = requests.GET.get("product_number")
        device_id = requests.GET.get("device_id")
        order_id = requests.GET.get("order_id")
        data = {
            "product_name": product_name if product_name else None,
            "product_number": product_number if product_number else None,
            "device_id": device_id if device_id else None,
            "order_id": order_id if order_id else None,
        }
        serializers = DeviceCheckSerializer(data=data)
        if serializers.is_valid():
            devices = DevicesModel.objects
            product_name = serializers.validated_data.get("product_name")
            product_number = serializers.validated_data.get("product_number")
            device_id = serializers.validated_data.get("device_id")
            order_id = serializers.validated_data.get("order_id")
            if product_name:
                devices = devices.filter(product_name__icontains=product_name)
            if product_number:
                devices = devices.filter(product_number__icontains=product_number)
            if device_id:
                devices = devices.filter(device_id__icontains=device_id)
            if order_id:
                devices = devices.filter(order_id__icontains=order_id)
            devices = devices.filter(is_delete=False).all()
            page = MyPageNumberPagination()
            page_usrs = page.paginate_queryset(queryset=devices, request=requests, view=self)
            gateway_re = DeviceListSerializer(instance=page_usrs, many=True)
            return Response(self.__get_paginated_response(page, requests, gateway_re.data))
        else:
            raise ValidationError(20001)

    def __get_paginated_response(self, page, request, datas):
        a = OrderedDict([
            ('current', int(page.get_page_number(request, page))),
            ('total', int(page.page.paginator.count)),
            ('pageSize', int(page.get_page_size(request))),
            ('data', datas),
            ("code", 200)

        ])
        return a

    @action(detail=False, methods=["POST", ], url_path="create")
    def productcreate(self, requests, *args, **kwargs):
        product_sum = requests.query_params.get("product_sum")
        device_id = requests.query_params.get("device_id")
        order_id = requests.query_params.get("order_id")
        mcu_id = requests.query_params.get("mcu_id")
        product_number = requests.query_params.get("product_number")
        product_name = requests.query_params.get("product_name")
        software_version = requests.query_params.get("software_version")
        hardware_version = requests.query_params.get("hardware_version")
        config_version = requests.query_params.get("config_version")
        data = {
            "product_sum": product_sum if product_sum else None,
            "device_id": device_id if device_id else None,
            "order_id": order_id if order_id else None,
            "mcu_id": mcu_id if mcu_id else None,
            "product_number": product_number if product_number else None,
            "product_name": product_name if product_name else None,
            "software_version": software_version if software_version else None,
            "hardware_version": hardware_version if hardware_version else None,
            "config_version": config_version if config_version else None,
        }
        serializer = DevicesCreateSerializer(data=requests.query_params)
        if serializer.is_valid():
            key = serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "添加成功"})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="update")
    def productupdate(self, requests, *args, **kwargs):
        id = requests.query_params.get("id")
        product_name = requests.query_params.get("product_name")
        product_number = requests.query_params.get("product_number")
        is_delete = requests.query_params.get("is_delete")
        data = {
            "id": id if id else None,
            "product_name": product_name if product_name else None,
            "product_number": product_number if product_number else None,
            "is_delete": is_delete if is_delete else None,
        }
        serializer = productUpdateSerializer(data=data)
        if serializer.is_valid():
            key = serializer.create(serializer.validated_data)
            return Response({"code": 200, "msg": "修改成功"})
        raise ValidationError(20001)

    @action(detail=False, methods=["GET", ], url_path="result_get")
    def result_get(self, requests, *args, **kwargs):
        device_id = requests.GET.get("device_id")
        data = {"device_id": device_id}
        serializer = DevicesConfigSingleGet(data=data)
        if serializer.is_valid():
            result = serializer.solve(serializer.validated_data)
            return Response({"code": 200, "data": result})
        else:
            raise ValidationError(20001)

    @action(detail=False, methods=["GET", ], url_path="row_result_get")
    def row_result_get(self, requests, *args, **kwargs):
        items = requests.GET
        data = {"items": dict(items)}
        serializer = DevicesConfigSerializer(data=data)
        if serializer.is_valid():
            result = serializer.solve(serializer.validated_data)
            return Response({"code": 200, "data": result})
        else:
            raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="row_result_set")
    def row_result_set(self, requests, *args, **kwargs):
        datas = dict(requests.query_params)
        ids = datas.get("ids")
        result = datas.get("result")
        data = {
            "ids": ids,
            "result": result
        }
        serializer = DevicesConfigSetSerializer(data=data)
        if serializer.is_valid():
            serializer.solve(serializer.validated_data)
        return Response({"code": 200, "result": result})

    @action(detail=False, methods=["GET", ], url_path="peizhi")
    def devicepeizhi(self, requests, *args, **kwargs):
        order_id = requests.GET.get("order_id")
        data = {
            "order_id": order_id
        }
        serializer = productpeizhiSerializer(data=data)
        if serializer.is_valid():
            results = serializer.create(serializer.validated_data)
            return Response({"code": 200, "results": results})
        raise ValidationError(20001)

    @action(detail=False, methods=["POST", ], url_path="huixie")
    def devicehuixie(self, requests, *args, **kwargs):
        sn_list = self.request.data.get("sn_list")
        data = {
            "sn_list": sn_list
        }
        serializer = producthuixieSerializer(data=data)
        if serializer.is_valid():
            serializer.create(serializer.validated_data)
            return Response({"code": 200})
        raise ValidationError(20001)
